<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'

// 定义比赛项目接口
interface GameEvent {
  eventID: number
  gameID: number
  eventName: string
  category: string
  description: string
  eventTime: string
  location: string
  maxParticipants: number
  currentParticipants: number
  status: string
}

// 响应式数据
const events = ref<GameEvent[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const gameId = ref<number | null>(null)
const currentPage = ref(1)
const pageSize = ref(2) // 每页显示2条数据

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(events.value.length / pageSize.value)
})

// 计算当前页的数据
const paginatedEvents = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return events.value.slice(startIndex, endIndex)
})

// 获取比赛项目信息
const fetchGameEvents = async (id: number) => {
  try {
    loading.value = true
    const token = localStorage.getItem('token')
    const response = await axios.get(`http://localhost:8080/event/getGameEvent?gameId=${id}`, {
      headers: {
        'token': token || ''
      }
    })
    
    if (response.data.success) {
      events.value = response.data.events
      error.value = null
    } else {
      error.value = '获取比赛项目信息失败'
    }
  } catch (err) {
    console.error('获取比赛项目信息失败:', err)
    error.value = '获取比赛项目信息失败'
  } finally {
    loading.value = false
  }
}

// 页面切换函数
const changePage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 初始化组件数据
const init = (id: number) => {
  gameId.value = id
  currentPage.value = 1 // 重置到第一页
  fetchGameEvents(id)
}

// 暴露方法给父组件
defineExpose({
  init
})

// 返回上一页
const goBack = () => {
  window.dispatchEvent(new CustomEvent('showGameEvent', {
    detail: { type: 'backToList' }
  }))
}

// 添加比赛项目
const addGameEvent = () => {
  window.dispatchEvent(new CustomEvent('showGameEvent', {
    detail: { type: 'showNewEventForm', gameId: gameId.value }
  }))
}

// 编辑比赛项目
const editGameEvent = (event: GameEvent) => {
  window.dispatchEvent(new CustomEvent('showGameEvent', {
    detail: { 
      type: 'editEventForm', 
      gameId: gameId.value,
      eventData: event
    }
  }))
}

// 删除比赛项目
const deleteGameEvent = async (event: GameEvent) => {
  if (!confirm(`确定要删除比赛项目 "${event.eventName}" 吗？`)) {
    return
  }
  
  try {
    const token = localStorage.getItem('token')
    const response = await axios.delete(`http://localhost:8080/event/delete?eventId=${event.eventID}`, {
      headers: {
        'token': token || ''
      }
    })
    
    if (response.data.success) {
      // 从列表中移除已删除的项目
      events.value = events.value.filter(e => e.eventID !== event.eventID)
      alert('删除成功')
    } else {
      alert('删除失败: ' + (response.data.message || '未知错误'))
    }
  } catch (err) {
    console.error('删除比赛项目失败:', err)
    alert('删除失败，请稍后重试')
  }
}

// 管理报名信息
const manageRegistrations = (event: GameEvent) => {
  window.dispatchEvent(new CustomEvent('showGameEvent', {
    detail: { 
      type: 'showEventRegisterForm', 
      eventId: event.eventID,
      gameId: gameId.value  // 同时传递gameId，以便在返回时使用
    }
  }))
}

onMounted(() => {
  // 组件挂载时的初始化逻辑可以在父组件中调用 init 方法完成
})
</script>

<template>
  <div class="game-event-management">
    <div class="header">
      <h2>比赛项目管理</h2>
      <div class="header-actions">
        <button class="back-button" @click="goBack">返回比赛列表</button>
        <button class="add-button" @click="addGameEvent">添加比赛项目</button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      数据加载中...
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error">
      {{ error }}
    </div>
    
    <!-- 数据展示 -->
    <div v-else class="events-container">
      <div v-if="events.length === 0" class="no-data">
        暂无比赛项目信息
      </div>
      
      <div v-else>
        <div class="events-list">
          <div 
            v-for="event in paginatedEvents" 
            :key="event.eventID" 
            class="event-card"
          >
            <h3>{{ event.eventName }}</h3>
            <div class="event-info">
              <p><strong>项目ID:</strong> {{ event.eventID }}</p>
              <p><strong>项目类别:</strong> {{ event.category }}</p>
              <p><strong>项目描述:</strong> {{ event.description }}</p>
              <p><strong>比赛时间:</strong> {{ new Date(event.eventTime).toLocaleString() }}</p>
              <p><strong>比赛地点:</strong> {{ event.location }}</p>
              <p><strong>参赛人数:</strong> {{ event.currentParticipants }} / {{ event.maxParticipants }}</p>
              <p><strong>项目状态:</strong> 
                <span :class="['status', event.status]">{{ event.status }}</span>
              </p>
            </div>
            <div class="event-actions">
              <button class="register-button" @click="manageRegistrations(event)">管理报名信息</button>
              <button class="edit-button" @click="editGameEvent(event)">编辑项目</button>
              <button class="delete-button" @click="deleteGameEvent(event)">删除项目</button>
            </div>
          </div>
        </div>
        
        <!-- 分页控件 -->
        <div class="pagination" v-if="totalPages > 1">
          <button 
            :disabled="currentPage === 1" 
            @click="changePage(currentPage - 1)"
            class="page-button"
          >
            上一页
          </button>
          
          <span class="page-info">
            第 {{ currentPage }} 页，共 {{ totalPages }} 页
          </span>
          
          <button 
            :disabled="currentPage === totalPages" 
            @click="changePage(currentPage + 1)"
            class="page-button"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.game-event-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  color: #333;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.add-button {
  background: linear-gradient(to right, #31B310, #2a990e);
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.add-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.back-button {
  background: #95a5a6;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: #7f8c8d;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.loading, .error, .no-data {
  text-align: center;
  padding: 40px 20px;
  font-size: 18px;
}

.error {
  color: #e74c3c;
}

.no-data {
  color: #7f8c8d;
}

.events-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(1, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.event-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  border-left: 5px solid #9b59b6;
  min-height: 400px; /* 设置最小高度使卡片更长 */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.event-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

.event-card h3 {
  color: #9b59b6;
  margin-top: 0;
  border-bottom: 2px solid #eee;
  padding-bottom: 10px;
}

.event-info {
  flex-grow: 1;
}

.event-info p {
  margin: 8px 0;
  color: #555;
}

.status {
  padding: 3px 8px;
  border-radius: 3px;
  font-weight: bold;
}

.status.未开始 {
  background-color: #95a5a6;
  color: white;
}

.status.筹划中 {
  background-color: #3498db;
  color: white;
}

.status.报名中 {
  background-color: #9b59b6;
  color: white;
}

.status.进行中 {
  background-color: #2ecc71;
  color: white;
}

.status.已结束 {
  background-color: #e74c3c;
  color: white;
}

.event-actions {
  margin-top: 15px;
  text-align: right;
}

.register-button {
  background: linear-gradient(to right, #9b59b6, #8e44ad);
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-left: 10px;
}

.register-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.edit-button, .delete-button {
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-left: 10px;
}

.edit-button {
  background: linear-gradient(to right, #3498db, #2980b9);
}

.delete-button {
  background: linear-gradient(to right, #e74c3c, #c0392b);
}

.edit-button:hover, .delete-button:hover, .register-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
}

.page-button {
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-button:hover:not(:disabled) {
  background: #2980b9;
  transform: translateY(-2px);
}

.page-button:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.page-info {
  color: #333;
  font-weight: bold;
}
</style>